<template>
  <div class="blog-container">
    <h2>目录</h2>
    <LevelList :list="newToc" @select="handleSelect" />
  </div>
</template>

<script>
import LevelList from "./LevelList.vue";
import debounce from "@/utils/debounce.js";
export default {
  components: {
    LevelList,
  },
  props: {
    toc: {
      type: Array,
    },
  },
  data() {
    return {
      selectedAnchor: "", //点击选中的anchor哈希值
    };
  },
  computed: {
    newToc() {
      var result = (toc = []) => {
        return toc.map((item) => {
          return {
            ...item,
            isSelect: item.anchor === this.selectedAnchor,
            children: result(item.children),
          };
        });
      };
      return result(this.toc);
    },
    doms() {
      //根据anchor拿到详情页的带有对应id的h标签
      var doms = [];
      var getDom = (toc) => {
        for (const item of toc) {
          doms.push(document.getElementById(item.anchor));
          if (item.children && item.children.length) {
            getDom(item.children);
          }
        }
      };
      getDom(this.toc);
      return doms;
    },
  },
  created() {
    this.newSet = debounce(this.setSelectAnchor, 50);
    // 监听事件     事件总线
    this.$bus.$on("mainScroll", this.newSet);
  },
  destroyed() {
    this.$bus.$off("mainScroll", this.newSet);
  },
  methods: {
    handleSelect(item) {
      //   console.log(item);
      location.hash = item.anchor;
    },
    setSelectAnchor(dom) {
      if (!dom) {
        return;
      }
      //根据dom元素位置设置selectedAnchor，决定选中项
      this.selectedAnchor = "";
      var range = 200;
      for (const item of this.doms) {
        if (!item) {
          continue;
        }
        var top = item.getBoundingClientRect().top;
        if (top >= 0 && top <= range) {
          this.selectedAnchor = item.id;
          return;
        } else if (top > range) {
          return;
        } else {
          this.selectedAnchor = item.id;
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
.blog-container {
  h2 {
    font-weight: bold;
    letter-spacing: 2px;
    font-size: 1em;
    margin: 0;
  }
}
</style>